import java.util.StringTokenizer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ReplyManager implements Runnable {
	private String result = null;
	private static ReplyManager instance = null;
	
    public static final String QUEUE_NAME = "NossToC4Queue";
	
	private ReplyManager() {
		(new Thread(this)).start();
	}

	public void run() {
		Context                 jndiContext = null;
	    QueueConnectionFactory  queueConnectionFactory = null;
	    QueueConnection         queueConnection;
	    QueueSession            queueSession;
	    Queue                   inQueue = null;
	    QueueReceiver           queueReceiver;
	    TextMessage             message;
	    Message					m;
	    
	    System.out.println("Starting Reply Listener ...");
        try {
            jndiContext = new InitialContext();
        } catch (NamingException e) {
            System.out.println("Could not create JNDI API " +
                "context: " + e.toString());
            System.exit(1);
        }
       
        /*
         * Look up connection factory and queue.  If either does
         * not exist, exit.
         */
        try {
            queueConnectionFactory = (QueueConnectionFactory)
                jndiContext.lookup("jms/ConnectionFactory");
            inQueue = (Queue) jndiContext.lookup(QUEUE_NAME);
        } catch (NamingException e) {
            System.out.println("JNDI API lookup failed: " +
                e.toString());
            System.exit(1);
        }

        /*
         * Create connection.
         * Create session from connection; false means session is
         * not transacted.
         * Create receiver, then start message delivery.
         * Receive all text messages from queue until
         * a non-text message is received indicating end of
         * message stream.
         * Close connection.
         */
        try {
            queueConnection =
                queueConnectionFactory.createQueueConnection("guest","guest");
            queueSession =
                queueConnection.createQueueSession(false,
                    Session.AUTO_ACKNOWLEDGE);
            queueReceiver = queueSession.createReceiver(inQueue);
            queueConnection.start();
           
            System.out.println("Listening to queue " + QUEUE_NAME + "....");
           
            while (true) {
                m = queueReceiver.receive(1);
                
                if (m != null) {
                    if (m instanceof TextMessage) {
                        message = (TextMessage) m;
                       
                        System.out.println("Reply Received... processing");
                        System.out.println(message.getText());
                        System.out.println();
                        
                        processReply(message.getText());

                    } else {
                        break;
                    }
                }
            }       
        } catch (JMSException e) {
            System.out.println("Exception occurred: " +
                e.toString());
        }
	}
	
	private void processReply(String xml) {
        StringTokenizer tokenizer;
        
        tokenizer = new StringTokenizer(xml,"\"");
		
		if (xml.indexOf("<ServiceRequestResponse") > -1) {
			for(int i = 0; i <=2; i++)
				tokenizer.nextToken();
			result = tokenizer.nextToken();

		}
		else {
			tokenizer.nextToken();
			result = tokenizer.nextToken();
		}
	}
	
	public String getReply() {
		String ret = null;
		if(result != null) {
			ret = new String(result);
			result = null;
		}
		return ret;
	}
	
	public static ReplyManager getReplyManager() {
		if(instance == null)
			instance = new ReplyManager();
		return instance;
	}
}
